<template>
	<view class="content">
		<z-paging ref="pagingRef" :data-list="dataList" @query="queryList" :fixed="false">
			<view class="item uni-flex uni-justify-between" v-for="(item, index) in dataList" :key="item.id"
				@click="itemClick(item)">
				<view class="item-box">
					<image class="left_img" referrerpolicy="no-referrer" :src="item.baseSmallImg" />
					<view class="uni-flex-item uni-flex uni-column uni-justify-between">
						<view class="title-box">
							<view class="title">{{item.itemName || '--'}}</view>
							<!-- 收藏图标：添加点击事件 -->
							<image
								:src="item.collect ? `${$ImgBaseUrl}lookforsb-collect-selected.png` : `${$ImgBaseUrl}detail_collect.png`"
								class='colletc' mode="widthFix" @click.stop="handleCollect(item, index)" />
						</view>

						<view class="desc">{{item.remark || '--'}}</view>
						<view class="uni-flex uni-justify-between uni-align-center">
							<view>
								<text class="price1">¥</text>
								<text
									class="price2">{{item.paramMinPrice || '--'}}-{{item.paramMaxPrice || '--'}}</text>
								<text class="text3">/{{item.paramPriceUnit || '--'}}</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 红色框中的元素 -->
				<view class="red-box" v-if="item.evaluate!==null">
					{{item.evaluate}}
				</view>
			</view>
			<template #empty>
				<view class="empty-container">
					<text>暂无数据</text>
				</view>
			</template>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		nextTick,
		reactive,
		toRefs,
		onUnmounted,
		onMounted,
		computed
	} from "vue";
	import {
		userCollectApi
	} from "@/api/personalFavorites.js";
	import {
		PeopleDetailCollect,
	} from '@/api/findPeople.js'

	const tabs1 = ref([]);
	const state = reactive({
		dataList: [],
		totalCount: 0, // 总条数
		currentGroupId: null,
		currentServiceId: null,
	});
	const {
		dataList,
		totalCount
	} = toRefs(state);
	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0
		},
		currentIndex: {
			type: Number,
			default: 0
		}, // 接收父组件当前索引
		browseType: {
			type: String,
			default: ''
		},
	});

	const emit = defineEmits(["reload"]);
	// 响应式数据
	const firstLoaded = ref(false);
	const isCurrentPage = ref(false);
	const pagingRef = ref(null);
	const isLoading = ref(false); // 控制收藏按钮加载状态

	// 监听currentIndex变化
	watch(
		() => props.currentIndex,
		(newVal) => {
			if (newVal === props.tabIndex) {
				if (!firstLoaded.value) {
					nextTick(() => {
						setTimeout(() => {
							firstLoaded.value = true;
							if (pagingRef.value) {
								pagingRef.value.reload();
							}
						}, 100);
					});
				} else {
					reload();
				}
			} else {
				firstLoaded.value = false;
			}
		}, {
			immediate: true
		}
	);


	// 调用接口获取数据
	const queryList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum: pageNum,
				pageSize: pageSize,
				browseType: props.browseType,
				// 根据实际需求添加其他参数
			};

			const res = await userCollectApi(params);
			if (res && res.code === 200) {
				const result = res.rows || [];
				// 分页逻辑处理
				if (pageNum === 1) {
					state.dataList = result;
				} else {
					state.dataList = [...state.dataList, ...result];
				}
				// 更新总条数（从接口返回的total字段获取）
				state.totalCount = res.total || 0;
				// 通知z-paging加载完成
				pagingRef.value.complete(result, pageNum * pageSize >= state.totalCount);
			} else {
				pagingRef.value.complete([], true);
			}
		} catch (error) {
			console.error('接口调用失败:', error);
			pagingRef.value.complete(false);
		}
	};

	// 暴露刷新方法给父组件
	const reload = () => {
		nextTick(() => {
			state.dataList = [];
			state.totalCount = 0;
			if (pagingRef.value) {
				// pagingRef.value.reload();
			}
		});
	};

	// 确保方法被正确暴露
	defineExpose({
		reload
	});


	// 点击item事件
	const itemClick = item => {
		console.log('点击item:', item);
		uni.navigateTo({
			url: "/pages/viewSonic/viewSonicDetail?id=" + item.id
		});
	};

	// 收藏/取消收藏逻辑（已同步第一个页面的逻辑）
	const handleCollect = async (item, index) => {
		// 防止重复点击
		if (isLoading.value) return;
		isLoading.value = true;

		try {
			// 调用收藏接口（isCollect取反当前状态）
			const res = await PeopleDetailCollect({
				collectId: item.id, // 物品ID
				collectType: 'VIEW_SONIC', // 固定类型（物品）
				isCollect: !item.collect // 切换收藏状态
			});

			if (res.code === 200) {
				// 关键修正：判断原状态是否为“已收藏”（取消收藏操作）
				if (item.collect) { 
					// 取消收藏：从列表中移除该项
					state.dataList.splice(index, 1);
					// 更新总条数（同步减少）
					state.totalCount--;
					uni.showToast({
						title: '取消收藏成功',
						icon: 'success',
						duration: 1500
					});
				} else {
					// 收藏操作：仅更新本地状态（不修改列表）
					item.collect = true;
					uni.showToast({
						title: '收藏成功',
						icon: 'success',
						duration: 1500
					});
				}

				// 通知分页组件刷新UI（同步列表变化）
				nextTick(() => {
					pagingRef.value.refresh();
				});

			} else {
				// 接口返回失败提示
				uni.showToast({
					title: res.msg || (item.collect ? '取消收藏失败' : '收藏失败'),
					icon: 'none',
					duration: 1500
				});
			}
		} catch (error) {
			// 捕获异常
			console.error('收藏接口调用失败:', error);
			uni.showToast({
				title: '操作失败，请重试',
				icon: 'none',
				duration: 1500
			});
		} finally {
			// 无论成功失败，都关闭加载状态
			isLoading.value = false;
		}
	};
</script>

<style lang="scss" scoped>
	/* 样式保持不变 */
	.content {
		padding-top: 14rpx;
		height: calc(100vh - 250rpx);
		background: #F5F5F5;
	}

	.box_2_tabs {
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.item {
		background: #ffffff;
		box-shadow: 0px 5rpx 20rpx 0px #e2e8f0;
		border-radius: 20rpx;
		padding: 24rpx 23rpx;
		margin: 26rpx 24rpx 0;
		display: flex;
		flex-direction: column;

		.item-box {
			display: flex;

			.title-box {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					font-weight: 500;
					font-size: 32rpx;
					color: #333333;
					line-height: 45rpx;
				}
			}
		}

		.red-box {
			background: #F4F4F4;
			color: #666666;
			padding: 5rpx 25rpx;
			border-radius: 8rpx;
			font-size: 24rpx;
			margin-top: 30rpx;
			height: 50rpx;
			display: flex;
			align-items: center;
		}

		.left_img {
			width: 203rpx;
			height: 203rpx;
			margin-right: 21rpx;
			border-radius: 20rpx;
		}

		.desc {
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
			line-height: 33rpx;
			margin-top: 15rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.price1 {
			font-size: 20rpx;
			color: #ff6a47;
		}

		.price2 {
			font-size: 32rpx;
			color: #ff6a47;
		}

		.text3 {
			font-weight: 400;
			font-size: 20rpx;
			color: #999999;
			line-height: 28rpx;
		}
	}

	.empty-container,
	.error-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}
	}

	.box-bottom {
		height: 50rpx;
		background: #F4F4F4;
		border-radius: 8rpx;
	}

	.colletc {
		width: 25rpx;
		height: 25rpx;
		display: block;
		touch-action: manipulation;

		&:active {
			opacity: 0.7;
		}
	}
</style>